package purchaseStore

import (
	"context"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"insighttracking/apps/admin/auth"
	"insighttracking/common/utils"
	"insighttracking/query/bo"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetPurchaseStorePageApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetPurchaseStorePageApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetPurchaseStorePageApiLogic {
	hostname, _ := os.Hostname()
	return &GetPurchaseStorePageApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetPurchaseStorePageApiLogic) GetPurchaseStorePageApi(req *types.GetPurchaseStorePageReq) (resp *types.GetPurchaseStorePageResp, err error) {
	// todo: add your logic here and delete this line
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return nil, err
	}
	pageBoResps, count, err := service.PurchaseStoreService.GetPurchaseStorePageApi(l.ctx, bo.GetPurchaseStorePageBoReq{
		EnterpriseID: accountInfo.EnterpriseId, // 关联到enterprise表主键id
		OrderNo:      req.OrderNo,              // 操作流水号
		StartDate:    req.StartDate,            // 开始时间  时间格式:2024-12-12 12:12:12
		EndDate:      req.EndDate,              // 结束时间  时间格式:2024-12-12 12:12:12
		WarehouseID:  req.WarehouseID,          // 入库仓,关联到warehouse表主键id
		PageSize:     req.PageSize,             // 当前条数
		PageNumber:   req.PageNumber,           // 当前页数
		Status:       req.Status,               // 状态,10表示部分收货,20表示全部收货,30是待入库
	})
	if err != nil {
		return &types.GetPurchaseStorePageResp{
			Data: make([]types.PurchaseStoreModel, 0),
			PageBaseResp: types.PageBaseResp{
				Total:      0,
				PageNumber: req.PageNumber,
				PageSize:   req.PageSize,
			},
		}, nil
	}
	operateIdList := k.Map(pageBoResps, func(item bo.GetPurchaseStorePageBoResp, index int) int64 {
		return item.OperateID
	})
	personEntities, err := service.EnterprisePersonService.GetByIdListApi(l.ctx, accountInfo.EnterpriseId, k.Distinct(operateIdList))
	var operateNameMap = make(map[int64]string)
	if err == nil && len(personEntities) > 0 {
		operateNameMap = k.ToMap(personEntities, func(item *model.EnterprisePersonEntity) (int64, string) {
			return item.ID, item.Name
		})
	}
	// 计算每笔订单的金额
	purchaseStoreIdList := k.Map(pageBoResps, func(item bo.GetPurchaseStorePageBoResp, index int) int64 {
		return item.ID
	})
	amountMap := service.PurchaseStoreDetailService.GetTotalAmountByPurchaseStoreIdListApi(l.ctx, purchaseStoreIdList)
	purchaseStoreModels := k.Map(pageBoResps, func(item bo.GetPurchaseStorePageBoResp, index int) types.PurchaseStoreModel {
		return types.PurchaseStoreModel{
			ID:                    item.ID,                                                                       // 主键id
			PurchaseOrdersID:      item.PurchaseOrdersID,                                                         // 采购单purchase_orders表主键id,如果是pc创建的时候为0
			PurchaseOrdersOrderNo: item.PurchaseOrdersOrderNo,                                                    // 采购单流水号
			OrderNo:               item.OrderNo,                                                                  // 操作流水号
			SupplierID:            item.SupplierID,                                                               // 供应商,关联到supplier表主键id
			SupplierName:          item.SupplierName,                                                             // 供应商名称
			PurchaserID:           item.PurchaserID,                                                              // 采购员,关联到
			PurchaserName:         item.PurchaserName,                                                            // 采购员名称
			OperateDate:           k.If(item.OperateDate.IsZero(), 0, utils.TimestampToString(item.OperateDate)), // 收货日期
			OperateName:           operateNameMap[item.OperateID],                                                // 制单员
			OperateID:             item.OperateID,                                                                // 制单员id,关联到员工表
			WarehouseID:           item.WarehouseID,                                                              // 入库仓,关联到warehouse表主键id
			WarehouseName:         item.WarehouseName,                                                            // 仓库名称
			TotalCount:            item.TotalCount.StringFixed(2),                                                // 采购总数量
			Source:                item.Source,                                                                   // 来源,0表示采购单生成,1表示手动创建单
			Types:                 item.Types,                                                                    // 类型,0表示供应商创建,1表示现场采购
			Status:                item.Status,                                                                   // 状态,10表示部分收货,20表示全部收货
			Remark:                item.Remark,                                                                   // 备注
			CreatedAt:             utils.TimestampToString(item.CreatedAt),                                       // 创建时间
			UpdatedAt:             utils.TimestampToString(item.UpdatedAt),                                       // 更新时间
			TotalAmount:           amountMap[item.ID].StringFixed(2),                                             //当前出库金额
			CreatedID:             item.CreatedID,                                                                // 创建人
			CreatedName:           item.CreatedName,                                                              //  创建人
		}
	})
	return &types.GetPurchaseStorePageResp{
		Data: purchaseStoreModels,
		PageBaseResp: types.PageBaseResp{
			Total:      count,
			PageNumber: req.PageNumber,
			PageSize:   req.PageSize,
		},
	}, nil

}
